﻿using System;
using System.Drawing;
using System.Collections.Generic;
using System.Windows.Forms;
using FBEntities;
using FBEntities.FBConnections.User;
using FBEntities.FBObjects;
using FBEntities.FBObjects.User;
using XDAFacebook;
using XFControls;
using XFControls.Utils;
using XFControls.XFPanels;
using XFControls.XFPanels.XFPanelItems;
using XFItemControls.XFPanels.XFPanelItems;
using XFSenseUI.XFItems;
using XFSenseUI.XFItems.SenseControls;
#pragma warning disable 1591

namespace XFItemControls.XFPanels
{
    public class XFPanelHomeIcon : XFPanelIcon
    {
        private readonly Dictionary<string, IXFIcon> _icons = new Dictionary<string, IXFIcon>();

        public XFPanelHomeIcon(Dictionary<int, string> homeIcons)
        {
            PanelName = Settings.LocalizationStrings.Home + ": " + XFItemControlUtils.Me.Me.name;
            IconSelectPanel();
            _bottom.MagnifyingGlass = true;
            _bottom.Album = true;
            _page = 1;
            _totalPages = 4;

            foreach (var homeIcon in homeIcons)
            {
                while (_items.Count <= homeIcon.Key)
                    Add(GenerateEmptyIcon(_items.Count));

                Add(_icons.ContainsKey(homeIcon.Value) ? _icons[homeIcon.Value] : new XFIconFriend(homeIcon.Value), homeIcon.Key);
            }
        }

        protected override XFPanelList AlbumPanel()
        {
            var ret = new XFPanelList { Settings.LocalizationStrings.comingSoon };
            ret.BackColor = Color.White;
            return ret;
        }

        protected override XFPanelList SearchPanel()
        {
            var ret = new XFPanelList { ScrollbarColor = Color.LightSlateGray };
            ret.ShowScrollbar(true);

            var search = new SenseItemTextBox { Description = Settings.LocalizationStrings.SearchInput };
            var type = new SenseItemDropDown { Description = Settings.LocalizationStrings.RequestType };
            type.Options.Add("Post");
            type.Options.Add("User");
            type.Selected = "Post";
            var button = new SenseItem { MainText = Settings.LocalizationStrings.PerformSearch };

            button.Click += GetSearchResults;

            ret.Add(search);
            ret.Add(type);
            ret.Add(button);

            return ret;
        }

        private void GetSearchResults(object sender, EventArgs e)
        {
            var button = sender as SenseItem;
            if (button == null || button.Parent == null) return;

            var parent = button.Parent as XFPanelList;
            if (parent == null) return;

            var search = parent[0] as SenseItemTextBox;
            var type = parent[1] as SenseItemDropDown;

            if (search == null || type == null) return;

            parent.ClearItems(parent[button] + 1);
            var worker = new XFWorkerGetSearch(search.Text, type.Selected);
            var loading = new XFItemLoading(worker);

            loading.WorkFinished += (o, ex) =>
            {
                var w = ex.Worker as XFWorkerGetSearch;
                if (parent.IsDisposed) return;

                parent.Invoke(new Action(() =>
                {
                    parent.ClearItemsAfterWaiting(o as XFItemLoading);

                    if (w != null)
                        foreach (var post in w.Search.data)
                        {
                            parent.Add(new XFItemPost(post));
                        }

                    Invalidate();
                }));
            };

            parent.Add(loading);
        }

        private void IconSelectPanel()
        {
            var fIcon = new XFIcon(Settings.LocalizationStrings.newsFeeds, "feeds");
            fIcon.Click += (o, e) => SetupNewsFeed();
            var feeds = new SenseItem { MainText = Settings.LocalizationStrings.newsFeeds, Tag = fIcon };
            _icons.Add("feeds", fIcon);

            var pIcon = new XFIcon(Settings.LocalizationStrings.Profile, "profile");
            pIcon.Click += (o, e) => SetupProfile();
            var profile = new SenseItem { MainText = Settings.LocalizationStrings.Profile, Tag = pIcon };
            _icons.Add("profile", pIcon);

            var frIcon = new XFIcon(Settings.LocalizationStrings.Friends, "friends");
            frIcon.Click += (o, e) => SetupFriends();
            var friends = new SenseItem { MainText = Settings.LocalizationStrings.Friends, Tag = frIcon };
            _icons.Add("friends", frIcon);

            var iIcon = new XFIcon(Settings.LocalizationStrings.Inbox, "inbox");
            iIcon.Click += (o, e) => SetupInbox();
            var inbox = new SenseItem { MainText = Settings.LocalizationStrings.Inbox, Tag = iIcon };
            _icons.Add("inbox", iIcon);

            var cIcon = new XFIcon(Settings.LocalizationStrings.Chat, "chat");
            cIcon.Click += (o, e) => SetupChat();
            var chat = new SenseItem { MainText = Settings.LocalizationStrings.Chat, Tag = cIcon };
            _icons.Add("chat", cIcon);

            var rIcon = new XFIcon(Settings.LocalizationStrings.Requests, "requests");
            rIcon.Click += (o, e) => SetupRequests();
            var requests = new SenseItem { MainText = Settings.LocalizationStrings.Requests, Tag = rIcon };
            _icons.Add("requests", rIcon);

            var eIcon = new XFIcon(Settings.LocalizationStrings.Events, "events");
            eIcon.Click += (o, e) => SetupEvents();
            var events = new SenseItem { MainText = Settings.LocalizationStrings.Events, Tag = eIcon };
            _icons.Add("events", eIcon);

            var plIcon = new XFIcon(Settings.LocalizationStrings.Places, "places");
            plIcon.Click += (o, e) => SetupPlaces();
            var places = new SenseItem { MainText = Settings.LocalizationStrings.Places, Tag = plIcon };
            _icons.Add("places", plIcon);

            var nIcon = new XFIcon(Settings.LocalizationStrings.Notes, "notes");
            nIcon.Click += (o, e) => SetupNotes();
            var notes = new SenseItem { MainText = Settings.LocalizationStrings.Notes, Tag = nIcon };
            _icons.Add("notes", nIcon);

            var aIcon = new XFIcon(Settings.LocalizationStrings.Albums, "albums");
            aIcon.Click += (o, e) => SetupPhotos();
            var albumns = new SenseItem { MainText = Settings.LocalizationStrings.Albums, Tag = aIcon };
            _icons.Add("albums", aIcon);

            var gIcon = new XFIcon(Settings.LocalizationStrings.Groups, "groups");
            gIcon.Click += (o, e) => SetupGroups();
            var groups = new SenseItem { MainText = Settings.LocalizationStrings.Groups, Tag = gIcon };
            _icons.Add("groups", gIcon);

            var usIcon = new XFIcon(Settings.LocalizationStrings.UpdateStatus, "updatestatus");
            usIcon.Click += (o, e) => SetupUpdateStatus();
            var updateStatus = new SenseItem { MainText = Settings.LocalizationStrings.UpdateStatus, Tag = usIcon };
            _icons.Add("updatestatus", usIcon);

            EmptyOptions.Add(FriendsPanel());
            EmptyOptions.Add(feeds);
            EmptyOptions.Add(profile);
            EmptyOptions.Add(friends);
            EmptyOptions.Add(inbox);
            EmptyOptions.Add(chat);
            EmptyOptions.Add(requests);
            EmptyOptions.Add(events);
            EmptyOptions.Add(places);
            EmptyOptions.Add(notes);
            EmptyOptions.Add(albumns);
            EmptyOptions.Add(groups);
            EmptyOptions.Add(updateStatus);
        }

        private IXFItem FriendsPanel()
        {
            var more = new SenseItemMoreItems { MainText = Settings.LocalizationStrings.SelectFriend, RightPanel = new XFPanelList() };

            var worker = new XFWorkerLoadFriends(XFItemControlUtils.Me.Me);

            var loading = new XFItemLoading(worker);
            loading.WorkFinished += (o, e) =>
                               {
                                   if (more.RightPanel.IsDisposed) return;
                                   int number = 0;

                                   if (more.RightPanel is XFPanelList && ((XFPanelList)more.RightPanel)[0].Tag != null)
                                       number = (int)((XFPanelList)more.RightPanel)[0].Tag;

                                   more.RightPanel.Invoke(new Action(() =>
                                   {
                                       XFItemControlUtils.SetupFriendSelector(more.RightPanel as XFPanelList, true);

                                       foreach (IXFItem item in (XFPanelList)more.RightPanel)
                                       {
                                           if (item.Tag == null) continue;
                                           item.Tag = new XFIconFriend((FBProxyPerson)item.Tag) { Number = number };

                                           item.Click -= ItemClick;
                                           item.Click += ItemClick;
                                       }
                                   }));
                               };

            ((XFPanelList)more.RightPanel).Add(loading);

            return more;
        }

        private void SetupUpdateStatus()
        {
            _curState = States.SlideLeft;

            var user = XFItemControlUtils.Me.Me;
            var input = new XFPanelTextInput();

            input.Submitted += (o, ex) =>
            {
                Cursor.Current = Cursors.WaitCursor;
                Application.DoEvents();

                var wrap = user.UpdateStatus(ex.Text);
                string res = wrap.Post();
                Cursor.Current = Cursors.Default;
            };

            SetRightPanel(input);
            input.PanelName = "Update Status";
        }

        private void SetupNewsFeed()
        {
            _curState = States.SlideLeft;

            var panel = new XFPanelList();


            if (!XFItemControlUtils.Me.Me.Home.Parsed)
            {
                var worker = new XFWorkerLoadNewsFeeds(XFItemControlUtils.Me.Me);
                var loading = new XFItemLoading(worker) { Async = false };

                loading.WorkFinished += SetupNewsFeedLoadingWorkFinished;

                panel.Add(loading);
            }
            else
            {
                var loading = new XFItemLoading();

                panel.OnFinishSlide += (o, e) => LoadFeeds(panel, XFItemControlUtils.Me.Me);

                panel.Add(loading);
            }

            SetRightPanel(panel);
            panel.ShowAlphaBar(false);
            panel.ShowScrollbar(true);
            panel.ScrollbarColor = Color.LightSlateGray;

            var home = new XFButtonHome();

            var parent = (XFPanelContainer)Parent;
            parent.SetHeaderRightButton(home);


            panel.PanelName = Settings.LocalizationStrings.newsFeeds;
        }

        private void SetupNewsFeedLoadingWorkFinished(object sender, WorkerEventArgs e)
        {
            FBCache.SaveCache();
            FBPerson parsedPers = null;
            var loading = (XFItemLoading)sender;
            if (e.Worker is XFWorkerLoadNewsFeeds)
                parsedPers = ((XFWorkerLoadNewsFeeds)e.Worker).ParsedPerson;

            var par = (XFPanelList)loading.Parent;

            if (!par.IsDisposed && parsedPers != null)
                par.InvokeEx(c => LoadFeeds(par, parsedPers));
        }

        private void LoadFeeds(XFPanelList par, FBPerson parsedPers)
        {
            par.ClearItems();
            var filter = new SenseItemDropDown
            {
                Selected = Settings.LocalizationStrings.none,
                Description = Settings.LocalizationStrings.FilterPosts
            };
            filter.SelectionChanged += (os, es) =>
            {
                if (es.Text == Settings.LocalizationStrings.none)
                {
                    foreach (IXFItem item in par)
                    {
                        if (item is XFItemPost)
                            item.Visible = true;
                    }
                }
                else
                {
                    foreach (IXFItem item in par)
                    {
                        if (item is XFItemPost)
                            item.Visible = ((XFItemPost)item).Post.type.Equals(es.Text, StringComparison.CurrentCultureIgnoreCase);
                    }
                }
                par.Resize();
                par.Invalidate();
            };

            filter.Options.Add(Settings.LocalizationStrings.none);
            filter.Options.Add("Status");
            filter.Options.Add("Link");
            filter.Options.Add("Video");
            filter.Options.Add("Photo");

            par.Add(filter);

            var load = new XFItemExpander
                      {
                          PreThresholdText = Settings.LocalizationStrings.PreThreshold,
                          PostThresholdText = Settings.LocalizationStrings.PostThreshold,
                          Max = Settings.ExpanderMax,
                          Threshold = Settings.ExpanderHeight
                      };

            load.ReleasePostThreshold += (o, e) =>
                                         {
                                             AsyncWebDownloader.ClearAsync();
                                             var loader = (XFItemExpander)o;
                                             var loaderPar = loader.Parent as XFPanelList;

                                             loader.Enabled = false;
                                             if (loaderPar == null) return;

                                             var worker = new XFWorkerLoadNewsFeeds(XFItemControlUtils.Me.Me);
                                             var newLoading = new XFItemLoading(worker);

                                             newLoading.WorkFinished += SetupNewsFeedLoadingWorkFinished;

                                             loaderPar.Add(newLoading, loaderPar[loader]);

                                         };
            par.AddExpander(load);

            if (parsedPers.Home != null)
                foreach (FBPost p in parsedPers.Home.data)
                {
                    var post = new XFItemPost(p);
                    par.Add(post);
                }
            else return;

            if (parsedPers.Home.paging == null) return;

            var next = new SenseItem
            {
                Tag = parsedPers.Home.paging.next,
                MainText = Settings.LocalizationStrings.olderPosts
            };

            next.Click += NextClick;
            next.Style.BackgroundColor = Color.White;
            par.Add(next);
        }

        private void NextClick(object sender, EventArgs e)
        {
            var button = (SenseItem)sender;
            var parent = (XFPanelList)button.Parent;

            parent.ClearItem(button);

            var worker = new XFWorkerLoadNewsFeeds(button.Tag.ToString());
            var loading = new XFItemLoading(worker);

            loading.WorkFinished += NextClickLoadingWorkFinished;
            button.Dispose();
            parent.Add(loading);
        }

        private void NextClickLoadingWorkFinished(object sender, WorkerEventArgs e)
        {
            FBHome home = null;
            var loading = (XFItemLoading)sender;

            if (e.Worker is XFWorkerLoadNewsFeeds)
                home = ((XFWorkerLoadNewsFeeds)e.Worker).Home;

            var par = loading.Parent as XFPanelList;
            string filter = GetFilter(par);

            if (par != null && !par.IsDisposed)
                par.Invoke(new Action(() =>
                {
                    par.ClearItemsAfterWaiting(loading);

                    if (home == null || home.data == null) return;
                    foreach (FBPost p in home.data)
                    {
                        var post = new XFItemPost(p);
                        if (!string.IsNullOrEmpty(filter) && !filter.Equals(Settings.LocalizationStrings.none))
                            post.Visible = filter.Equals(post.Post.type, StringComparison.CurrentCultureIgnoreCase);
                        par.Add(post);
                        par.RenderItemBuffer(post, false);
                    }

                    if (home.paging == null) return;
                    var next = new SenseItem
                    {
                        Tag = home.paging.next,
                        MainText = Settings.LocalizationStrings.olderPosts
                    };

                    next.Click += NextClick;
                    next.Style.BackgroundColor = Color.White;
                    par.Add(next);
                }));
        }

        private static string GetFilter(XFPanelList parent)
        {
            foreach (IXFItem item in parent)
            {
                if (item is SenseItemDropDown)
                    return ((SenseItemDropDown)item).Selected;
            }
            return "";
        }

        private void SetupProfile()
        {
            _curState = States.SlideLeft;

            XFPanelList panel = XFItemControlUtils.SetupProfile(XFItemControlUtils.Me.Me);

            SetRightPanel(panel);
            panel.ShowAlphaBar(false);
            panel.ShowScrollbar(true);

            var home = new XFButtonHome();

            var parent = (XFPanelContainer)Parent;
            parent.SetHeaderRightButton(home);

            panel.PanelName = Settings.LocalizationStrings.Profile;
        }

        private void SetupFriends()
        {
            _curState = States.SlideLeft;

            FBDataSource ds = XFItemControlUtils.Me ?? new FBDataSource("False");
            var panel = new XFPanelList();


            if (!ds.Me.Friends.Parsed)
            {
                var worker = new XFWorkerLoadFriends(ds.Me);
                var loading = new XFItemLoading(worker);

                loading.WorkFinished += LoadingFriendsWorkFinished;

                panel.Add(loading);
                loading.DoWork();
            }
            else
            {
                AddFriends(panel, ds);
            }
            panel.ScrollbarColor = Color.LightSlateGray;

            SetRightPanel(panel);
            panel.ShowAlphaBar(true);
            panel.ShowScrollbar(true);

            var home = new XFButtonHome();

            var parent = (XFPanelContainer)Parent;
            parent.SetHeaderRightButton(home);

            panel.PanelName = Settings.LocalizationStrings.Friends;
        }

        private void AddFriends(XFPanelList panel, FBDataSource ds)
        {
            if (panel.InvokeRequired)
            {
                if (!panel.IsDisposed)
                    panel.Invoke(new XFItemControlUtils.AddFriendsDel(AddFriends), panel, ds);
                return;
            }

            panel.ClearItems();

            var load = new XFItemExpander
            {
                PreThresholdText = Settings.LocalizationStrings.PreThreshold,
                PostThresholdText = Settings.LocalizationStrings.PostThreshold,
                Max = Settings.ExpanderMax,
                Threshold = Settings.ExpanderHeight
            };

            load.ReleasePostThreshold += (o, e) =>
            {
                AsyncWebDownloader.ClearAsync();
                var loader = (XFItemExpander)o;
                var loaderPar = loader.Parent as XFPanelList;

                loader.Enabled = false;
                if (loaderPar == null) return;

                var worker = new XFWorkerLoadFriends(ds.Me);
                var loading = new XFItemLoading(worker);

                loading.WorkFinished += LoadingFriendsWorkFinished;

                loaderPar.Add(loading, loaderPar[loader]);
                loading.DoWork();

            };
            panel.AddExpander(load);

            XFItemControlUtils.AddFriends(panel, ds);
        }

        void LoadingFriendsWorkFinished(object sender, WorkerEventArgs e)
        {
            FBCache.SaveCache();
            FBDataSource dsInner = XFItemControlUtils.Me ?? new FBDataSource("False");
            var l = (XFItemLoading)sender;
            AddFriends((XFPanelList)l.Parent, dsInner);
        }

        private void SetupInbox()
        {
            _curState = States.SlideLeft;

            FBDataSource ds = XFItemControlUtils.Me ?? new FBDataSource("False");
            var panel = new XFPanelList();
            var inbox = new FBInbox();

            var worker = new XFWorkerLoadInbox(ds.Me);
            var loading = new XFItemLoading(worker);

            loading.WorkFinished += (o, e) =>
                                    {
                                        FBDataSource dsInner = XFItemControlUtils.Me ?? new FBDataSource("False");
                                        var l = (XFItemLoading)o;
                                        XFItemControlUtils.AddMailItems((XFPanelList)l.Parent, dsInner);
                                    };

            var compose = new SenseItem
                          {
                              MainText = Settings.LocalizationStrings.Compose,
                          };

            compose.Click += (o, e) => MessageBox.Show(Settings.LocalizationStrings.CantSendMessage);
            compose.Style.BackgroundColor = Color.White;

            panel.Add(compose);
            panel.Add(loading);
            loading.DoWork();

            panel.ScrollbarColor = Color.LightSlateGray;

            foreach (FBMail item in inbox.data)
            {
                panel.Add(new XFItemPost(item.ToPost()));
            }

            SetRightPanel(panel);
            panel.ShowAlphaBar(false);
            panel.ShowScrollbar(true);

            var home = new XFButtonHome();

            var parent = (XFPanelContainer)Parent;
            parent.SetHeaderRightButton(home);

            panel.PanelName = Settings.LocalizationStrings.Inbox;
        }

        private void SetupChat()
        {
            _curState = States.SlideLeft;

            var panel = XFChat.GetChatPanel();

            SetRightPanel(panel);
            panel.ShowAlphaBar(false);
            panel.ShowScrollbar(true);
            panel.ScrollbarColor = Color.LightSlateGray;

            var home = new XFButtonHome();

            var parent = (XFPanelContainer)Parent;
            parent.SetHeaderRightButton(home);

            panel.PanelName = Settings.LocalizationStrings.Chat;
        }

        private void SetupRequests()
        {
            _curState = States.SlideLeft;

            XFPanelList panel = GetRequestsPanel(Parent);
            SetRightPanel(panel);
        }

        public static XFPanelList GetRequestsPanel(Control parent)
        {
            var panel = new XFPanelList();

            if (parent != null && parent is XFPanelContainer && ((XFPanelContainer)parent).UpdateNotification != null)
            {
                IUpdateable rawNotification = ((XFPanelContainer)parent).UpdateNotification;
                rawNotification.Show = false;
                if (rawNotification is FBNotifications)
                {
                    var notifications = (FBNotifications)rawNotification;

                    //FBNotificationObject nots = notifications.GetNotifictaions();
                    panel.Add(new SenseItemDivider { Text = Settings.LocalizationStrings.notifications });

                    var worker = new XFWorkerLoadNotifications(notifications);
                    var loading = new XFItemLoading(worker);

                    loading.WorkFinished += SetupRequestsLoadingWorkFinished;

                    panel.Add(loading);
                }
            }


            panel.ShowAlphaBar(false);
            panel.ShowScrollbar(true);
            panel.ScrollbarColor = Color.LightSlateGray;

            var home = new XFButtonHome();

            var par = (XFPanelContainer)parent;

            if (par != null)
                par.SetHeaderRightButton(home);

            panel.PanelName = Settings.LocalizationStrings.Requests;
            return panel;
        }

        private static void SetupRequestsLoadingWorkFinished(object sender, WorkerEventArgs e)
        {
            bool newNotifications = true;
            var loading = (XFItemLoading)sender;
            var panel = loading.Parent as XFPanelList;
            List<FBNotificationListObject> list = ((XFWorkerLoadNotifications)e.Worker).Notifications.GetNotificationList();

            if (panel != null && !panel.IsDisposed)
                panel.Invoke(new Action(() =>
                {
                    panel.ClearItemsAfterWaiting(loading);
                    foreach (FBNotificationListObject l in list)
                    {
                        if (newNotifications && l.unread == 0)
                        {
                            newNotifications = false;
                            panel.Add(new SenseItemDivider { Text = Settings.LocalizationStrings.notificationsRead });
                        }

                        var note = new XFItemNotificationList(l);
                        note.ReadButton.Clicked += (oc, ec) =>
                        {
                            var listObject = (FBNotificationListObject)((SenseControlButton)oc).Tag;
                            Cursor.Current = Cursors.WaitCursor;
                            Application.DoEvents();

                            listObject.MarkAsRead();
                            ((SenseControlButton)oc).Disabled = true;
                            list.Remove(listObject);

                            Cursor.Current = Cursors.Default;
                            Application.DoEvents();
                        };

                        if (l.unread == 0)
                            note.ReadButton.Disabled = true;
                        note.ReadButton.Tag = l;
                        panel.Add(note);
                    }
                    var clearAll = new SenseItem
                    {
                        MainText = Settings.LocalizationStrings.clearAll
                    };

                    clearAll.Click += (co, ce) =>
                    {
                        Cursor.Current = Cursors.WaitCursor;
                        Application.DoEvents();

                        foreach (FBNotificationListObject item in list)
                        {
                            item.MarkAsRead();
                        }

                        var clear = new List<int>();
                        foreach (IXFItem item in panel)
                        {
                            if (item is XFItemNotificationList)
                                clear.Add(panel[item]);
                        }

                        foreach (int i in clear)
                            panel.ClearItem(i);

                        Cursor.Current = Cursors.Default;
                        Application.DoEvents();

                        panel.Resize();
                        MessageBox.Show(Settings.LocalizationStrings.allNotificationsCleared);
                    };
                    clearAll.Style.BackgroundColor = Color.White;

                    panel.Add(clearAll);
                }));
        }

        private void SetupEvents()
        {
            _curState = States.SlideLeft;

            FBDataSource ds = XFItemControlUtils.Me ?? new FBDataSource("False");
            var panel = new XFPanelList();

            var invites = new SenseItemDivider
            {
                Text = Settings.LocalizationStrings.InvitedEvents
            };

            panel.Add(invites);
            bool pendingInvites = false;

            if (Parent != null && Parent is XFPanelContainer && ((XFPanelContainer)Parent).UpdateNotification != null)
            {
                IUpdateable rawNotification = ((XFPanelContainer)Parent).UpdateNotification;
                if (rawNotification is FBNotifications)
                {
                    var notifications = (FBNotifications)rawNotification;
                    FBNotificationObject nots = notifications.GetNotifictaions();

                    if (nots == null)
                    {
                        Cursor.Current = Cursors.WaitCursor;
                        Application.DoEvents();

                        notifications.ManualUpdate();

                        Cursor.Current = Cursors.Default;
                        Application.DoEvents();
                    }

                    if (nots != null)
                    {
                        foreach (long id in nots.EventRequests)
                        {
                            var ev = new FBEvent { id = id.ToString() };
                            ev.Parse();
                            panel.Add(new XFItemEvent(ev));
                            pendingInvites = true;
                        }
                    }
                }
            }

            if (!pendingInvites)
                panel.ClearItem(invites);


            var events = new SenseItemDivider
            {
                Text = Settings.LocalizationStrings.RespondedEvents
            };

            panel.Add(events);

            var worker = new XFWorkerLoadEvents(ds.Me);
            var loading = new XFItemLoading(worker);

            loading.WorkFinished += (o, e) =>
            {
                FBPerson usr = ((XFWorkerLoadEvents)e.Worker).ParsedPerson;
                var l = (XFItemLoading)o;

                var par = (XFPanelList)l.Parent;
                if (!par.IsDisposed)
                    par.Invoke(new Action(() =>
                    {
                        if (par.HasItem(l))
                        {
                            par.ClearItemsAfterWaiting(l);
                            foreach (
                                FBEvent @event in usr.Events.data)
                                panel.Add(new XFItemEvent(@event));
                        }
                    }));
            };

            panel.Add(loading);

            SetRightPanel(panel);
            panel.ShowAlphaBar(false);
            panel.ShowScrollbar(true);
            panel.ScrollbarColor = Color.LightSlateGray;

            var home = new XFButtonHome();

            var parent = (XFPanelContainer)Parent;
            if (parent != null) parent.SetHeaderRightButton(home);

            panel.PanelName = Settings.LocalizationStrings.Events;
        }

        private void SetupPhotos()
        {
            _curState = States.SlideLeft;

            XFPanelList panel = XFItemControlUtils.SetupUserAlbums(XFItemControlUtils.Me.Me);

            SetRightPanel(panel);
            panel.ShowAlphaBar(false);
            panel.ShowScrollbar(true);
            panel.ScrollbarColor = Color.LightSlateGray;

            var home = new XFButtonHome();

            var parent = (XFPanelContainer)Parent;
            parent.SetHeaderRightButton(home);

            panel.PanelName = Settings.LocalizationStrings.Photos;
        }

        private void SetupNotes()
        {
            _curState = States.SlideLeft;

            FBDataSource ds = XFItemControlUtils.Me ?? new FBDataSource("False");
            var panel = new XFPanelList();

            var worker = new XFWorkerLoadNotes(ds.Me);
            var loading = new XFItemLoading(worker);
            var notes = new FBNotes();

            loading.WorkFinished += (o, e) =>
            {
                FBDataSource dsInner = XFItemControlUtils.Me ?? new FBDataSource("False");
                var l = (XFItemLoading)o;
                XFItemControlUtils.AddNotes((XFPanelList)l.Parent, dsInner);
            };

            var compose = new SenseItem
            {
                MainText = Settings.LocalizationStrings.Compose,
                ClickResults = XFItemClickResult.SlideLeft
            };

            compose.Click += (o, e) =>
            {
                XFPanelList cPanel = XFItemControlUtils.SetupNotes();
                cPanel.Add(new XFItemBackHeader());

                panel.SetRightPanel(cPanel);
            };
            compose.Style.BackgroundColor = Color.White;

            panel.Add(compose);
            panel.Add(loading);
            panel.ScrollbarColor = Color.LightSlateGray;

            SetRightPanel(panel);
            panel.ShowAlphaBar(false);
            panel.ShowScrollbar(true);

            var home = new XFButtonHome();

            var parent = (XFPanelContainer)Parent;
            parent.SetHeaderRightButton(home);

            loading.DoWork();
            panel.PanelName = Settings.LocalizationStrings.Notes;
        }

        private void SetupPlaces()
        {
            _curState = States.SlideLeft;

            XFPanelList panel = XFItemControlUtils.SetupPlaces();

            SetRightPanel(panel);
            panel.ShowAlphaBar(false);
            panel.ShowScrollbar(true);
            panel.ScrollbarColor = Color.LightSlateGray;

            var home = new XFButtonHome();

            var parent = (XFPanelContainer)Parent;
            parent.SetHeaderRightButton(home);

            panel.PanelName = Settings.LocalizationStrings.Places;
        }

        private void SetupGroups()
        {
            _curState = States.SlideLeft;

            var panel = new XFPanelList();


            if (!XFItemControlUtils.Me.Me.Groups.Parsed)
            {
                var worker = new XFWorkerLoadGroups(XFItemControlUtils.Me.Me);
                var loading = new XFItemLoading(worker) { Async = false };

                loading.WorkFinished += SetupGroupsLoadingWorkFinished;

                panel.Add(loading);
            }
            else
            {
                var loading = new XFItemLoading();

                panel.OnFinishSlide += (o, e) => LoadGroups(panel, XFItemControlUtils.Me.Me);

                panel.Add(loading);
            }

            SetRightPanel(panel);
            panel.ShowAlphaBar(false);
            panel.ShowScrollbar(true);
            panel.ScrollbarColor = Color.LightSlateGray;

            var home = new XFButtonHome();

            var parent = (XFPanelContainer)Parent;
            parent.SetHeaderRightButton(home);


            panel.PanelName = Settings.LocalizationStrings.Groups;
        }

        private void SetupGroupsLoadingWorkFinished(object sender, WorkerEventArgs e)
        {
            FBCache.SaveCache();
            FBPerson parsedPers = null;
            var loading = (XFItemLoading)sender;
            if (e.Worker is XFWorkerLoadGroups)
                parsedPers = ((XFWorkerLoadGroups)e.Worker).ParsedPerson;

            var par = (XFPanelList)loading.Parent;

            if (!par.IsDisposed && parsedPers != null)
                par.InvokeEx(c => LoadGroups(par, parsedPers));
        }

        private void LoadGroups(XFPanelList par, FBPerson parsedPers)
        {
            par.ClearItems();

            if (parsedPers.Groups != null)
                foreach (var p in parsedPers.Groups.data)
                {
                    var post = new XFItemPost(p.ToPost());
                    post.Tag = p;
                    par.Add(post);
                }
            else return;
        }

        protected override void SaveState()
        {
            var homeIcons = new Dictionary<int, string>();

            for (int i = 0; i < _items.Count; i++)
            {
                if (_items[i].Icon == "plus") continue;
                homeIcons.Add(i, _items[i].Icon);
            }

            Settings.HomeIcons = homeIcons;
            Settings.SaveSettings();
        }
    }
}
#pragma warning restore 1591
